// Solitaire for HTML5
// tepaanan@gmail.com

// Mouse pos
var mousex=0, mousey=0;

// Mouse click and card's upper left corner offset
var xOff=0, yOff=0;

// Mouse offset between moves
var moveXAmount=0;
var moveYAmount=0;

// Card size
var cardHeight=110;
var cardWidth=75;
var cardInitVal=0;

// Canvas
var canvas
var ctx;
var tmpCanvas;
var tmpCtx;

// Is mouse down
var mouseDown=false;

// For cards
var activeCard=undefined;
var cardLoadingIndex=0;
var cardArray = new Array();
var cardNameArray = new Array();
var movingCardsDrawed  = true;

var generalGraphicsArray = new Array();
var generalGraphicsLoadingIndex = 0;

// Deck types
var DeckType = {
    Foundation:1,
    Waste:2,
    Stock:3,
    Target:4
};

// Card lands
var CardLand = {
    Club:1,
    Diamond:2,
    Heart:3,
    Spade:4
};

// For decks
var deck1 = new DeckObject(DeckType.Foundation,0,0);
var deck2 = new DeckObject(DeckType.Foundation,0,0);
var deck3 = new DeckObject(DeckType.Foundation,0,0);
var deck4 = new DeckObject(DeckType.Foundation,0,0);
var deck5 = new DeckObject(DeckType.Foundation,0,0);
var deck6 = new DeckObject(DeckType.Foundation,0,0);
var deck7 = new DeckObject(DeckType.Foundation,0,0);
var stock = new DeckObject(DeckType.Stock,0,0);
var waste = new DeckObject(DeckType.Waste,0,0);
var target1 = new DeckObject(DeckType.Target,0,0);
var target2 = new DeckObject(DeckType.Target,0,0);
var target3 = new DeckObject(DeckType.Target,0,0);
var target4 = new DeckObject(DeckType.Target,0,0);

// Background
var background = new Image();
var cardBackground = new Image();
var deckBackground = new Image();

// Loading graphics -message
var message;

// Window resize event
var resizeTimer = undefined;
var documentWidth = 0;
var documentHeight = 0;


/******************************************************************************
 * requestAnimFrame
 * http://www.html5canvastutorials.com/labs/html5-canvas-ultimate-flash-killer/
 */ 
window.requestAnimFrame = (function(callback){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

/******************************************************************************
 * Card object
 * http://www.javascriptkit.com/javatutors/object2.shtml
 */ 
function CardObject(id, x, y, img){
    // Properties
    this.id = id;
    this.land = 0;
    this.deckId = 0;
    this.isTurned = false;
    this.deckObject = undefined;
    this.x = x;
    this.y = y;
    this.oldX = x;
    this.oldY = y;
    this.img = img;
    this.topCard = undefined;
    this.isBlack = false;
    // Methods
    this.cancel = _CardObject_cancel;
    this.move = _CardObject_move;
    this.storePos = _CardObject_storePos;
    this.drawCard = _CardObject_drawCard;
}
function _CardObject_drawCard(ctx,drawAlsoTopCard) {
    // Draw this card
    if (this.isTurned) {
        ctx.drawImage(this.img,this.x,this.y,cardWidth,cardHeight);
    } else {
        ctx.drawImage(cardBackground,this.x,this.y,cardWidth,cardHeight);
    }
    // And also its top cards if needed
    if (drawAlsoTopCard && this.topCard) {
        this.topCard.drawCard(ctx,drawAlsoTopCard);
    }
}
function _CardObject_storePos(x,y) {
    this.x = x;
    this.y = y;
    this.oldX = x;
    this.oldY = y;
}
function _CardObject_move(x,y) {
    if (this.isTurned) {
        this.x = x;
        this.y = y;
        if (this.topCard) {
            this.topCard.move(x, y + cardHeight * 0.2);
        }
    }
}
function _CardObject_cancel() {
    this.x = this.oldX;
    this.y = this.oldY;
    if (this.topCard) {
        this.topCard.cancel();
    }
}


/******************************************************************************
 * Deck object
 */ 
function DeckObject(id, x, y){
    // Properties
    this.id = id;
    this.x = x;
    this.y = y;
    this.cardArray = new Array();
    // Methods
    this.setPos = _DeckObject_setPos;
    this.addCard = _DeckObject_addCard;
    this.cardUnderMouse = _DeckObject_cardUnderMouse;
    this.deckUnderMouse = _DeckObject_deckUnderMouse;
    this.drawDeck = _DeckObject_drawDeck;
    this.removeTopCard = _DeckObject_removeTopCard;
    this.removeFromThisCard = _DeckObject_removeFromThisCard;
}
function _DeckObject_drawDeck(ctx) {
    for(var i=0 ; i < this.cardArray.length ; i++) {
        var card = this.cardArray[i];
        // Do not draw active card and its top cards
        if (card!=activeCard) {
            card.drawCard(ctx,false);
        } else {
            return;
        }
    }
}
function _DeckObject_setPos(x,y){
    this.x = x;
    this.y = y;
}
function _DeckObject_addCard(card){
    var yCap = cardHeight * 0.2;
    // Set new position for the card
    if (this.id == DeckType.Foundation) {
        card.storePos(this.x,this.y + yCap * this.cardArray.length);
    } else {
        card.storePos(this.x,this.y);
    }
    // Store new deck data into card
    card.deckId = this.id; 
    card.deckObject = this;   
 
    // Set new card as top card of previous top
    if(this.cardArray.length > 0) {
        this.cardArray[this.cardArray.length-1].topCard = card;
    }
     // Add new card into deck array
    this.cardArray.push(card);
    
    // Add top card into this deck
    if (card.topCard) {
        this.addCard(card.topCard);
    }
}
function _DeckObject_removeTopCard() {
    // Get top most card
    var card = this.cardArray.pop();
    
    // Reset old top card data
    if(this.cardArray.length > 0) {
        this.cardArray[this.cardArray.length-1].topCard = undefined;
        //this.cardArray[this.cardArray.length-1].isTurned = true;
    }
    return card;
}
function _DeckObject_removeFromThisCard(card) {
    // Remove all card from the deck starting from this card
    for(var i=0;i<this.cardArray.length;i++) {
        if (card != this.cardArray[this.cardArray.length-1]) {
            this.cardArray.pop();
            i--;
        } else if (card == this.cardArray[this.cardArray.length-1]) {
            this.cardArray.pop();
            if(this.cardArray.length > 0) {
                this.cardArray[this.cardArray.length-1].topCard = undefined;
                this.cardArray[this.cardArray.length-1].isTurned = true;
            }
            return;
        }
    }
}
function _DeckObject_cardUnderMouse(x,y){
    for(var i=this.cardArray.length-1;i>=0;i--) {
        var card = this.cardArray[i];
        if (card.x < x && card.y < y && card.x+cardWidth > x && card.y+cardHeight > y) {
            return card;
        }
    }
    return undefined;
}
function _DeckObject_deckUnderMouse(x,y) {
    var yCap = cardHeight * 0.2 * this.cardArray.length;
    if (this.id != DeckType.Foundation) {
        if (this.x < x && this.y < y && this.x+cardWidth > x && this.y+cardHeight > y) {
            return this;
        }
    } else {
        if (this.x < x && this.y < y && this.x+cardWidth > x && this.y+cardHeight+yCap > y) {
            return this;
        }
    }
    return undefined;
}

/******************************************************************************
 * Solitaire game logic
 * Check is the move allowed
 */ 
function isAllowedMove(fromDeck, toDeck, card) {
    // Get card that will be under this new card
    var topOfCard = undefined;
    if (toDeck.cardArray.length > 0)
        topOfCard = toDeck.cardArray[toDeck.cardArray.length-1];

    // Check deck issues        
    if (topOfCard && topOfCard.isTurned == false)
        return false;
    if (fromDeck.id != DeckType.Foundation && fromDeck.id != DeckType.Waste)
        return false;
    if (toDeck.id != DeckType.Foundation && toDeck.id != DeckType.Target)
        return false;
    
    // Card's decks must differ    
    if (fromDeck == toDeck)
        return false;

    // Check card's issues
    if(toDeck.cardArray.length>0) {
        if (toDeck.id == DeckType.Foundation) {
        // Card can be top of one step greater card and different color
        // Card can not be same color
        if (card.land == topOfCard.land || topOfCard.id != card.id + 1 || card.isBlack == topOfCard.isBlack)
            return false;
        } else if (toDeck.id == DeckType.Target) {
            // Cards must be in ascending order and same suite in 2 target deck
            if (topOfCard.id + 1 != card.id || topOfCard.land != card.land) 
                return false;
        }
    } else {
        // Moving top of empty deck
        // If there is no cards in the deck, then the first one must be King card in source decks 1
        if (toDeck.cardArray.length == 0 && card.id != 13 && toDeck.id == DeckType.Foundation)
            return false;

        // Ace card must be the first card in foundation
        if (toDeck.id == DeckType.Target && toDeck.cardArray.length == 0 && card.id != 1)
            return false;
    }
    
        
    return true;
}


/******************************************************************************
 * Clear canvas
 * TODO: Not in use
 */ 
function clearCanvas(x,y,w,h) {
    // Whole canvas
    ctx.clearRect(0,0,canvas.width,canvas.height);
}


/******************************************************************************
 * Window resize event handling
 */ 
function resizeEvent(event) {
    if(resizeTimer) {
        clearTimeout(resizeTimer);
        resizeTimer = undefined;
    }
    resizeTimer = setTimeout("doResize()",300); 
}
function doResize() {
    resizeTimer = undefined;
    // TODO: is that good solution?
    // TODO: some reloading loop in Safari
    //window.location.reload();
}


/******************************************************************************
 * Draw fast single card
 * Draw only dirty background behind the card
 * Draw active moving card on top of all others
 */ 
function drawCardFast(cardToDraw, toContext, toBackground) {
    // Draw dirty background behind the card
    if (toBackground) {
        if (cardToDraw.topCard) {
        toContext.drawImage(toBackground, cardToDraw.x-moveXAmount, 0, cardWidth+moveXAmount*2, canvas.height, 
            cardToDraw.x-moveXAmount, 0, cardWidth+moveXAmount*2, canvas.height);
        } else {
        toContext.drawImage(toBackground, cardToDraw.x-moveXAmount, cardToDraw.y-moveYAmount, cardWidth+moveXAmount*2, cardHeight+moveYAmount*2, 
            cardToDraw.x-moveXAmount, cardToDraw.y-moveYAmount, cardWidth+moveXAmount*2, cardHeight+moveYAmount*2 );
        }
    }
    // Draw card and its parent cards
    cardToDraw.drawCard(toContext,true);
}

/******************************************************************************
 * Copy whole canvas and draw it once
 * Starts showing copy of the original canvas
 */ 
function copyCanvasAndDraw() {
    // Draw target canvas to ready for copying it
    ctx.drawImage(background,0,0,documentWidth,documentHeight);

    // Target backgrounds
    var capX = (canvas.width - (7 * cardWidth)) / 8; 
    ctx.drawImage(deckBackground,cardWidth*3+capX*4,capX,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*4+capX*5,capX,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*5+capX*6,capX,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*6+capX*7,capX,cardWidth,cardHeight);

    // Draw decks
    deck1.drawDeck(ctx);
    deck2.drawDeck(ctx);
    deck3.drawDeck(ctx);
    deck4.drawDeck(ctx);
    deck5.drawDeck(ctx);
    deck6.drawDeck(ctx);
    deck7.drawDeck(ctx);
    stock.drawDeck(ctx);
    waste.drawDeck(ctx);
    target1.drawDeck(ctx);
    target2.drawDeck(ctx);
    target3.drawDeck(ctx);
    target4.drawDeck(ctx);
    

    // Draw target canvas to temporary canvas
    tmpCtx.drawImage(canvas, 0, 0);

    // And active card on that
    if (activeCard) {
        activeCard.drawCard(tmpCtx,true);
    }

    // Change temporary canvas to visible
    canvas.style.display="none";
    tmpCanvas.style.display="block";
}

/******************************************************************************
 * Set original canvas back to visible 
 */ 
function resetCanvas() {
    canvas.style.display="block";
    tmpCanvas.style.display="none";
}

/******************************************************************************
 * Draw all
 */ 
function drawAll() {
    // Background
    ctx.drawImage(background,0,0,documentWidth,documentHeight);

    // Target backgrounds
    var capX = (canvas.width - (7 * cardWidth)) / 8; 
    ctx.drawImage(deckBackground,cardWidth*3+capX*4,capX,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*4+capX*5,capX,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*5+capX*6,capX,cardWidth,cardHeight);
    ctx.drawImage(deckBackground,cardWidth*6+capX*7,capX,cardWidth,cardHeight);
    
    // Draw decks
    deck1.drawDeck(ctx);
    deck2.drawDeck(ctx);
    deck3.drawDeck(ctx);
    deck4.drawDeck(ctx);
    deck5.drawDeck(ctx);
    deck6.drawDeck(ctx);
    deck7.drawDeck(ctx);
    stock.drawDeck(ctx);
    waste.drawDeck(ctx);
    target1.drawDeck(ctx);
    target2.drawDeck(ctx);
    target3.drawDeck(ctx);
    target4.drawDeck(ctx);

    // Draw active card lates to get it on top of all rest
    if (activeCard) {
        activeCard.drawCard(ctx,true);
    }
}


/******************************************************************************
 * Initialize general graphics
 */ 
function initGeneralGraphics() {

    // TODO: Image.onload does not work in Safari

    if (generalGraphicsLoadingIndex==0) {
        background.onload  = function(){
            initGeneralGraphics();
            //setTimeout(initGeneralGraphics, 500);
        }; 
        background.src = generalGraphicsArray[generalGraphicsLoadingIndex];
    } else if (generalGraphicsLoadingIndex==1) {
        cardBackground.onload  = function(){
            initGeneralGraphics();
            //setTimeout(initGeneralGraphics, 500);
        }; 
        cardBackground.src = generalGraphicsArray[generalGraphicsLoadingIndex];
    } else if (generalGraphicsLoadingIndex==2) {
        deckBackground.onload  = function(){
            initGeneralGraphics();
            //setTimeout(initGeneralGraphics, 500);
        }; 
        deckBackground.src = generalGraphicsArray[generalGraphicsLoadingIndex];
    } else {
        initCards();
    }
    
    generalGraphicsLoadingIndex++;
    updateMessage('Downloading general graphics...');
    
}
    
/******************************************************************************
 * Initialize cards and load card graphics
 */ 
function initCards() {
    updateMessage('Downloading graphics for cards... '+cardLoadingIndex+' / ' + cardNameArray.length); 

    if (cardNameArray.length == cardLoadingIndex) {
        message.style.display='none';
        // All loaded
        initDecks();
        return;
    }

    // Create card object    
    var card = new CardObject(1,0,0,undefined);
    card.img = new Image();
    var landVal = (cardLoadingIndex+1) / 13;
    if (landVal<=1) {
        card.land = CardLand.Club;
        card.isBlack = true;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    } else if (landVal>1 && landVal<=2) {
        card.land = CardLand.Diamond;
        card.isBlack = false;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    } else if (landVal>2 && landVal<=3) {
        card.land = CardLand.Heart;
        card.isBlack = false;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    } else {
        card.land = CardLand.Spade;
        card.isBlack = true;
        if (cardInitVal > 12)
            cardInitVal = 0;
        cardInitVal++;
    }
    card.id = cardInitVal;
    card.img.onload = function(){
        initCards();
        //setTimeout(initCards, 100);
    };
    card.img.src = cardNameArray[cardLoadingIndex];
    cardArray.push(card);
    cardLoadingIndex++; 
}

/******************************************************************************
 * Create all game decks
 */ 
function initDecks() {

    // Mess cards first
    for (var i=0;i<300;i++) {
        var randNro1=Math.floor(Math.random()*cardArray.length);
        var card1 = cardArray[randNro1];
        var randNro2=Math.floor(Math.random()*cardArray.length);
        var card2 = cardArray[randNro2];
        cardArray[randNro1] = card2;
        cardArray[randNro2] = card1;
    }
    
    // Deal cards into decks
    var capX = (canvas.width - (7 * cardWidth)) / 8; 
    var yPos = capX * 2 + cardHeight;
    var index = 0;

    deck1.setPos(capX,yPos);
    deck1.addCard(cardArray[index++]);
    deck1.cardArray[deck1.cardArray.length-1].isTurned = true;

    deck2.setPos(cardWidth*1+capX*2,yPos);
    deck2.addCard(cardArray[index++]);
    deck2.addCard(cardArray[index++]);
    deck2.cardArray[deck2.cardArray.length-1].isTurned = true;

    deck3.setPos(cardWidth*2+capX*3,yPos);
    deck3.addCard(cardArray[index++]);
    deck3.addCard(cardArray[index++]);
    deck3.addCard(cardArray[index++]);
    deck3.cardArray[deck3.cardArray.length-1].isTurned = true;

    deck4.setPos(cardWidth*3+capX*4,yPos);
    deck4.addCard(cardArray[index++]);
    deck4.addCard(cardArray[index++]);
    deck4.addCard(cardArray[index++]);
    deck4.addCard(cardArray[index++]);
    deck4.cardArray[deck4.cardArray.length-1].isTurned = true;

    deck5.setPos(cardWidth*4+capX*5,yPos);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.addCard(cardArray[index++]);
    deck5.cardArray[deck5.cardArray.length-1].isTurned = true;

    deck6.setPos(cardWidth*5+capX*6,yPos);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.addCard(cardArray[index++]);
    deck6.cardArray[deck6.cardArray.length-1].isTurned = true;

    deck7.setPos(cardWidth*6+capX*7,yPos);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.addCard(cardArray[index++]);
    deck7.cardArray[deck7.cardArray.length-1].isTurned = true;

    stock.setPos(capX,capX);
    while (index < cardArray.length -1) {
        stock.addCard(cardArray[index++]);
    }
    waste.setPos(cardWidth*1+capX*2,capX);
    waste.addCard(cardArray[index++]);
    waste.cardArray[waste.cardArray.length-1].isTurned = true;
    
    target1.setPos(cardWidth*3+capX*4,capX);
    target2.setPos(cardWidth*4+capX*5,capX);
    target3.setPos(cardWidth*5+capX*6,capX);
    target4.setPos(cardWidth*6+capX*7,capX);
    
    // All created
    drawAll();
}

/******************************************************************************
 * Update message to the user
 */ 
function updateMessage(text) {
    message.innerHTML = text;
}


/******************************************************************************
 * Initialize canvas for drawing and load graphics
 */ 
function init() {
    // Document size
    documentWidth = document.body.offsetWidth;
    documentHeight = document.body.offsetHeight;

    // Card size
    cardHeight=documentWidth / 7;
    cardWidth=cardHeight / 1.46;

    // Main canvas for drawing surface
    canvas = document.getElementById('deskCanvas');
    canvas.width = documentWidth - canvas.offsetLeft*2;
    canvas.height = documentHeight - canvas.offsetTop;
    canvas.style.display="block";
    ctx = document.getElementById('deskCanvas').getContext('2d');


    // Add the temporary canvas where main canvas is copied/drawed in mousedown
    // Temporary canvas is drawed in mousemove
    var container = canvas.parentNode;
    tmpCanvas = document.createElement('canvas');
    tmpCanvas.style.display="none";
    tmpCanvas.id     = 'tmpDeskCanvas';
    tmpCanvas.width  = canvas.width;
    tmpCanvas.height = canvas.height;
    tmpCanvas.offsetLeft = canvas.offsetLeft;
    tmpCanvas.offsetRight = canvas.offsetRight;
    container.appendChild(tmpCanvas);
    tmpCtx = tmpCanvas.getContext('2d');    
        
    // Loading graphics message
    message = document.getElementById('message');

    // Mouse events
    canvas.addEventListener('mousedown', ev_mousedown, false);
    canvas.addEventListener('mousemove', ev_mousemove, false);
    tmpCanvas.addEventListener('mousemove', ev_mousemove, false);
    canvas.addEventListener('mouseup',   ev_mouseup, false);
    tmpCanvas.addEventListener('mouseup',   ev_mouseup, false);

    // Card names
    cardLoadingIndex = 0;
    cardNameArray.push('gfx/Club_ace.png');
    cardNameArray.push('gfx/Club_2.png');
    cardNameArray.push('gfx/Club_3.png');
    cardNameArray.push('gfx/Club_4.png');
    cardNameArray.push('gfx/Club_5.png');
    cardNameArray.push('gfx/Club_6.png');
    cardNameArray.push('gfx/Club_7.png');
    cardNameArray.push('gfx/Club_8.png');
    cardNameArray.push('gfx/Club_9.png');
    cardNameArray.push('gfx/Club_10.png');
    cardNameArray.push('gfx/Club_jack.png');
    cardNameArray.push('gfx/Club_queen.png');
    cardNameArray.push('gfx/Club_king.png');
    cardNameArray.push('gfx/Diamond_ace.png');
    cardNameArray.push('gfx/Diamond_2.png');
    cardNameArray.push('gfx/Diamond_3.png');
    cardNameArray.push('gfx/Diamond_4.png');
    cardNameArray.push('gfx/Diamond_5.png');
    cardNameArray.push('gfx/Diamond_6.png');
    cardNameArray.push('gfx/Diamond_7.png');
    cardNameArray.push('gfx/Diamond_8.png');
    cardNameArray.push('gfx/Diamond_9.png');
    cardNameArray.push('gfx/Diamond_10.png');
    cardNameArray.push('gfx/Diamond_jack.png');
    cardNameArray.push('gfx/Diamond_queen.png');
    cardNameArray.push('gfx/Diamond_king.png');
    cardNameArray.push('gfx/Heart_ace.png');
    cardNameArray.push('gfx/Heart_2.png');
    cardNameArray.push('gfx/Heart_3.png');
    cardNameArray.push('gfx/Heart_4.png');
    cardNameArray.push('gfx/Heart_5.png');
    cardNameArray.push('gfx/Heart_6.png');
    cardNameArray.push('gfx/Heart_7.png');
    cardNameArray.push('gfx/Heart_8.png');
    cardNameArray.push('gfx/Heart_9.png');
    cardNameArray.push('gfx/Heart_10.png');
    cardNameArray.push('gfx/Heart_jack.png');
    cardNameArray.push('gfx/Heart_queen.png');
    cardNameArray.push('gfx/Heart_king.png');
    cardNameArray.push('gfx/Spade_ace.png');
    cardNameArray.push('gfx/Spade_2.png');
    cardNameArray.push('gfx/Spade_3.png');
    cardNameArray.push('gfx/Spade_4.png');
    cardNameArray.push('gfx/Spade_5.png');
    cardNameArray.push('gfx/Spade_6.png');
    cardNameArray.push('gfx/Spade_7.png');
    cardNameArray.push('gfx/Spade_8.png');
    cardNameArray.push('gfx/Spade_9.png');
    cardNameArray.push('gfx/Spade_10.png');
    cardNameArray.push('gfx/Spade_jack.png');
    cardNameArray.push('gfx/Spade_queen.png');
    cardNameArray.push('gfx/Spade_king.png');

    // General graphics
    generalGraphicsLoadingIndex = 0;
    generalGraphicsArray.push('gfx/background.png');
    generalGraphicsArray.push('gfx/card_background.png');
    generalGraphicsArray.push('gfx/deck_background.png');
    
    // Start loading general graphics
    initGeneralGraphics();
    
}

/******************************************************************************
 * Find card under mouse coordinates
 */ 
function cardUnderMouse(x,y) {
    // Find card under user mouse press
    var card = undefined;

    if(card = deck1.cardUnderMouse(x,y)) return card;
    if(card = deck2.cardUnderMouse(x,y)) return card;
    if(card = deck3.cardUnderMouse(x,y)) return card;
    if(card = deck4.cardUnderMouse(x,y)) return card;
    if(card = deck5.cardUnderMouse(x,y)) return card;
    if(card = deck6.cardUnderMouse(x,y)) return card;
    if(card = deck7.cardUnderMouse(x,y)) return card;
    if(card = waste.cardUnderMouse(x,y)) return card;
    if(card = stock.cardUnderMouse(x,y)) return card;

    return undefined;
}

/******************************************************************************
 * Find deck under mouse coordinates
 */ 
function deckUnderMouse(x,y) {
    // Find deck under user mouse press
    var deck = undefined;

    if(deck = deck1.deckUnderMouse(x,y)) return deck;
    if(deck = deck2.deckUnderMouse(x,y)) return deck;
    if(deck = deck3.deckUnderMouse(x,y)) return deck;
    if(deck = deck4.deckUnderMouse(x,y)) return deck;
    if(deck = deck5.deckUnderMouse(x,y)) return deck;
    if(deck = deck6.deckUnderMouse(x,y)) return deck;
    if(deck = deck7.deckUnderMouse(x,y)) return deck;
    if(deck = waste.deckUnderMouse(x,y)) return deck;
    if(deck = stock.deckUnderMouse(x,y)) return deck;
    if(deck = target1.deckUnderMouse(x,y)) return deck;
    if(deck = target2.deckUnderMouse(x,y)) return deck;
    if(deck = target3.deckUnderMouse(x,y)) return deck;
    if(deck = target4.deckUnderMouse(x,y)) return deck;
    
    return undefined;
}

/******************************************************************************
 * Mouse down
 */ 
function ev_mousedown (ev) {
    if (mouseDown)
        return;
    
    mouseDown = true;
    mousex = ev.clientX - canvas.offsetLeft;
    mousey = ev.clientY - canvas.offsetTop;
        
    activeCard = cardUnderMouse(mousex,mousey);
    var activeDeck = deckUnderMouse(mousex,mousey);
    
    // User wants more cards from stock to waste
    if ((activeCard && activeCard.deckId == DeckType.Stock) || 
        (activeDeck && activeDeck.id == DeckType.Stock) ) {
        if (activeCard && stock.cardArray.length > 0) {
            // Do move from stock to waste
            stock.removeTopCard();
            activeCard.topCard = undefined;
            activeCard.isTurned = true;
            waste.addCard(activeCard);
        } else {
            // Stock is empty, copy card back from waste
            var card = waste.removeTopCard();
            while(card) {
                card.topCard = undefined;
                card.isTurned = false;
                stock.addCard(card);
                card = waste.removeTopCard();
            }
        }
        mouseDown = false;
        activeCard = undefined;
        return;
    }

    // User starts moving cards
    if (activeCard) {
        xOff = mousex - activeCard.x;
        yOff = mousey - activeCard.y;
        // Copy main canvas and start drawing copy of it
        copyCanvasAndDraw();
    } else {
        mouseDown = false;
    }    
}

/******************************************************************************
 * Mouse move
 */ 
function ev_mousemove (ev) {
    if (!mouseDown)
        return;

    if (!activeCard) {
        return;
    }
        
    var newX = ev.clientX - tmpCanvas.offsetLeft;
    var newY = ev.clientY - tmpCanvas.offsetTop;

   
    // Is mouse position outside of canvas?
    var tmpX = newX - xOff;
    var tmpY = newY - yOff;
    if (tmpX < 1 || 
        tmpX + cardWidth >= canvas.width) {
        // MouseUp
        mouseDown = false;
        // Cancel move
        activeCard.cancel();
        activeCard = undefined;
        // Draw whole main canvas
        drawAll();
        // Start showing again main canvas
        resetCanvas();
        return;
    }


    // Move card
    if (movingCardsDrawed) {
        moveXAmount = Math.abs(mousex - newX) +2;
        moveYAmount = Math.abs(mousey - newY) +2;
        movingCardsDrawed = false;
    } else {
        moveXAmount += Math.abs(mousex - newX) +2;
        moveYAmount += Math.abs(mousey - newY) +2;
    }
    
    mousex = newX;
    mousey = newY;
    activeCard.move(mousex - xOff, mousey - yOff);
    
    // request new frame
    requestAnimFrame(function(){
        drawCardFast(activeCard,tmpCtx,canvas);
        movingCardsDrawed = true;
    });
 
}


/******************************************************************************
 * Mouse up
 */ 
function ev_mouseup (ev) {
    mouseDown = false;
    mousex=0;
    mousey=0;

    var x = ev.clientX - tmpCanvas.offsetLeft;
    var y = ev.clientY - tmpCanvas.offsetTop;

    // Change card into different deck
    if (activeCard) {
        var activeDeck = deckUnderMouse(x,y);
        if (activeDeck) {
            if (isAllowedMove(activeCard.deckObject, activeDeck, activeCard)) {
                // Remove cards from the original deck
                activeCard.deckObject.removeFromThisCard(activeCard);
                // Add cards into new deck
                activeDeck.addCard(activeCard);
            } else {
                activeCard.cancel();
            }
        } else {
            activeCard.cancel();
        }
    }
   
    activeCard = undefined;

    // Draw whole main canvas
    drawAll();
    // Start showing again main canvas
    resetCanvas();
    
    movingCardsDrawed = true;
} 
